package com.distribute.application.manage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;

import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.distribute.application.api.utils.DateUtils;
import com.distribute.framework.model.*;
import com.distribute.framework.plugin.*;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.helper.ConfigHelper;
import com.alibaba.fastjson.JSON;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.RelateClass;
import com.distribute.framework.core.lang.caption;
import com.distribute.framework.core.lang.hidden;
import com.distribute.framework.core.lang.note;
import com.distribute.framework.core.lang.primary;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.helper.ConfigHelper;

@RestController(value="manage.applicationController")
public class ApplicationController {
	
	
	@RequestMapping("/manage/config.action")
	public Protocol config() {
		try{
			Protocol protocol = Protocol.create(true);
			if(LoginHelper.getLogin()!=null){
				protocol.set("username", LoginHelper.getLogin().getKeyValue());
			}
			protocol.set("lzFlashUrl", Utils.config("upload.lzFlashUrl"));
			protocol.set("uploadUrl", Utils.config("upload.uploadUrl"));
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	
	@RequestMapping("/manage/menu.do")
	public Protocol menu() {
		try{
			Protocol protocol = Protocol.create(true);
			String strJson = Utils.readFile(ApplicationController.class.getResourceAsStream("projects.json"), "UTF-8");
			List list = (List) JSON.parse(strJson);
			/************APP_DEFINE_MENU************/
			/************APP_DEFINE_MENU************/
			protocol.set("projects", list);
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	
	@RequestMapping("/manage/login.action")
	public Protocol login() { 
		try{
			String strRequestSyscode=Utils.getString("syscode");
		    String strSessionSyscode = Utils.getSession("syscode");
			Utils.removeSession("syscode");
			if (strRequestSyscode == null || !strRequestSyscode.equals(strSessionSyscode)){
				return Protocol.create(false, "对不起，验证码输入错误！");
			}
			String strUsername=Utils.getString("username");
			String strPassword=Utils.getString("password");		
			if(strUsername==null || strUsername.trim().equals("")){
				return Protocol.create(false, "对不起，帐号输入为空！");
			}
			if(strPassword==null || strPassword.trim().equals("")){
				return Protocol.create(false, "对不起，密码输入为空！");
			}
			
			//TODOK:请在这里实现登录的逻辑
			Manage manage = Manage.where.username(strUsername).get();
			if(manage==null){
				return Protocol.create(false, "用户不存在");
			}else if(!manage.getPassword().equals(strPassword) && !Utils.md5(manage.getPassword()).equals(Utils.md5(strPassword))){
				return Protocol.create(false, "对不起，密码输入错误");
			}else{
				Merchant login = Merchant.where.id(manage.getMerchant()).get();
				LoginHelper.setLogin(login);
				LoginHelper.setUser(manage);
			}
			return Protocol.create(true);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	@RequestMapping("/manage/logout.do")
	public Protocol logout() {
		try{
			LoginHelper.setLogin(null);
			Utils.setSession("manage_login", null);
			Utils.setSession("manage_login_id",null);
			Utils.setSession("session_like_host", null);
			Utils.setCookie("/", "UID", null);
			return Protocol.create(true);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	@RequestMapping("/manage/header.do")
	public Protocol header() {
		return Protocol.create(true);
	}
	
	@RequestMapping("/manage/welcome.do")
	public Protocol welcome() {
		Protocol protocol = Protocol.create(true);
		
		protocol.set("brandAccount", BrandAccount.where.brand(LoginHelper.getLogin().getId()).get());
		
		Calendar calendar = java.util.Calendar.getInstance();
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		protocol.set("today", Utils.date(calendar.getTime(), "yyyy年MM月dd日,星期E"));
		//冲增订单数
		protocol.set("chongzcount", ProductOrder.where.merchant(LoginHelper.getLogin().getId()).paymentStatus((short)1).count());
		//已支付代理订单数
		protocol.set("dlordercount", AgentCardOrder.where.merchant(LoginHelper.getLogin().getId()).payStatus((short)2).count());
		//已支付合伙人订单数
		protocol.set("hhrcount", TbPartnerCardOrder.where.merchant(LoginHelper.getLogin().getId()).payStatus((short)2).count());
		//当前会员人数
		protocol.set("membercount", Member.where.count());
		//当前代理数
		protocol.set("dailicount", Agent.where.merchant(LoginHelper.getLogin().getId()).count());
		//今日新增代理数
		//protocol.set("todydailicount", Agent.where.addTimeStart(DateUtils.getTimesmornings()).addTimeEnd(DateUtils.getTimesnights()).count());
		//当前合伙人数
		protocol.set("hhrcount", TbPartners.where.tbpBrand(LoginHelper.getLogin().getId()).count());
		//今日新增合伙人数
		//protocol.set("todyhhrcount", TbPartners.where.tbpPayCard((short)2).tbpAddTimeStart(DateUtils.getTimesmornings()).tbpAddTimeEnd(DateUtils.getTimesnights()).count());
		//会员提现
		//protocol.set("hytxcount", MembershipRecord.where.auditType((short)1).count());
		//配送商提现
		//protocol.set("tixiancount", DistributorCash.where.approvalStatus((short)1).count());
		protocol.set("counts0", DirectOrder.where.merchant(LoginHelper.getLogin().getId()).addTimeStart(calendar.getTime()).statusIn("2,3,4,5,6").count());
		protocol.set("counts1", DirectOrder.where.merchant(LoginHelper.getLogin().getId()).addTimeStart(calendar.getTime()).statusIn("2,3,4,5,6").eval("sum(total_sum)"));
		protocol.set("counts2", Member.where.addTimeStart(calendar.getTime()).count());
		protocol.set("counts3", DirectOrder.where.merchant(LoginHelper.getLogin().getId()).status(1).count());
		//今日充值成功订单
		protocol.set("counts4", ProductOrder.where.merchant(LoginHelper.getLogin().getId()).addTimeStart(new Date(DateUtils.getTimesmorning())).addTimeEnd(new Date(DateUtils.getTimesnight())).paymentStatus((short)1).status(1).count());
		//今日售后订单
		protocol.set("counts5", DirectOrder.where.merchant(LoginHelper.getLogin().getId()).updateTimeStart(new Date(DateUtils.getTimesmorning())).updateTimeEnd(new Date(DateUtils.getTimesnight())).status(5).count());
		//今日新赠代理
		protocol.set("counts6", AgentCardOrder.where.merchant(LoginHelper.getLogin().getId()).addTimeStart(new Date(DateUtils.getTimesmorning())).addTimeEnd(new Date(DateUtils.getTimesnight())).payStatus((short)2).count());
		//今日新增合伙人
		protocol.set("counts7", TbPartnerCardOrder.where.merchant(LoginHelper.getLogin().getId()).addTimeStart(new Date(DateUtils.getTimesmorning())).addTimeEnd(new Date(DateUtils.getTimesnight())).payStatus((short)2).count());
		protocol.set("orders", DirectOrder.where.merchant(LoginHelper.getLogin().getId()).statusNot(7).desc("id").list(5), new BeanFormat<DirectOrder>(){
			@Override
			public Map format(DirectOrder t) {
				return t.toJSON();
			}
		});
		
		protocol.set("agents", AgentCardOrder.where.merchant(LoginHelper.getLogin().getId()).statusNot(-1).desc("id").list(5), new BeanFormat<AgentCardOrder>(){
			@Override
			public Map format(AgentCardOrder t) {
				return t.toJSON();
			}
		});
		
		protocol.set("products", ProductOrder.where.merchant(LoginHelper.getLogin().getId()).statusNot(-1).desc("id").list(5), new BeanFormat<ProductOrder>(){
			@Override
			public Map format(ProductOrder t) {
				return t.toJSON();
			}
		});
		
		calendar.add(Calendar.DATE, -12);
		List<Map> stats = DirectOrder.where.merchant(LoginHelper.getLogin().getId()).statusNot(7).addTimeStart(calendar.getTime()).stats(DirectOrder.C.totalSum, DirectOrder.C.addTime, 4);
		Map<String,String> homebars = new HashMap();
		String category = "";
		String values = "";
		for(Map item:stats){
			if(!category.equals(""))category+=",";
			if(!values.equals(""))values+=",";
			values+="'"+item.get("value")+"'";
			category+="'"+item.get("name")+"'";
		}
		homebars.put("category", category);
		homebars.put("values", values);
		homebars.put("title", "总金额");
		protocol.set("homebars", homebars);		
		
		return protocol;
	}
	@RequestMapping("/manage/modify.do")
	public Protocol modify(){
		try{
			String strOld=Utils.getString("old");
			String strNew=Utils.getString("now");
			if(!strNew.matches("((?=.*\\d)(?=.*\\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^.{8,16}$")){
				return Protocol.create(false, "密码格式错误，必须是8到16位字符，不能为纯数字或纯字母");
			}
			
			//TODO:请在这里实现修改密码的逻辑
			return Protocol.create(false, "密码修改功能未实现");	
		}catch(Exception ex){
			ex.printStackTrace();
			return Protocol.create(false, "系统错误,请稍候再试");
		}
	}
	
	@RequestMapping("/manage/vcode.action")
	public Protocol vcode() {
		Utils.getRandcode();
		return null;
	}
	
	
	@RequestMapping("/manage/struct.do")
	public String struct() {
		String className = Utils.getString("className");
		try {
			List fields = parseClass(className,Utils.getInteger("depth",0));
			return JSON.toJSONString(fields);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static List parseClass(String className,int maxDepth) throws Exception{
		return parseClass(className,new ArrayList(),"",0,maxDepth);
	}
	public static List parseClass(String calssName,List list,String parentKey,int depth,int maxDepth) throws Exception{
		if(depth>maxDepth)
			return list;
		Class<?> cls = Class.forName(calssName);
		Map<String,Boolean> fmaping = new HashMap();
		try{
			Class FClass = Class.forName(calssName+"$F");
			if(FClass!=null){
				Field[] Ffields = FClass.getFields();
				for(Field field:Ffields){
					fmaping.put(field.getName(), true);
				}
			}
		}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
		Field[] fields = cls.getDeclaredFields();
		Map<String,String> names = new HashMap();
		for(Field field:fields){			
			caption caption = field.getAnnotation(caption.class);	
			note note = field.getAnnotation(note.class);
			RelateClass relateClass = field.getAnnotation(RelateClass.class);
			if(caption!=null && field.getAnnotation(hidden.class)==null){
				Map map = new HashMap();
				if(Utils.empty(parentKey))
					map.put("name",field.getName());
				else{
					map.put("name",parentKey+"."+field.getName());
					map.put("parent",parentKey.replace("[]", ""));
				}
				map.put("depth", depth);
				map.put("caption", caption.value());	
				map.put("type", field.getType().getName());
				map.put("primary", field.getAnnotation(primary.class)!=null);
				if(note!=null && note.value().indexOf("'")==-1 && note.value().indexOf("lz:")==-1 && note.value().indexOf("{")==-1)
					map.put("note", note.value());
				if(fmaping.get(field.getName()+"Start")!=null || fmaping.get(field.getName()+"Min")!=null)
					map.put("range","true");
				if(relateClass!=null)
					map.put("relate",relateClass.value().getSimpleName());
				list.add(map);
				if(relateClass!=null){ 
					//Utils.trace(caption.value(),relateClass.value().getName(),field.getType(),field.getType()==List.class);
					parseClass(relateClass.value().getName(),list,Utils.str(map.get("name"))+(field.getType()==List.class?"[]":""),depth+1,maxDepth);
				}		
			}
		}
		return list;		
	}
	
}